//
//  MapViewController.m
//  Clock
//
//  Created by Zc on 16/4/10.
//  Copyright © 2016年 qianfeng. All rights reserved.
//

#import "MapViewController.h"
#import "tool.h"
#import "ZCScreenAd.h"
#import "FucViewController.h"
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width
#define LABELTAG 423424

@interface MapViewController ()<BMKMapViewDelegate, BMKGeoCodeSearchDelegate, BMKLocationServiceDelegate, BMKPoiSearchDelegate, UITextFieldDelegate>
{
    UIView * _topView;
    NSInteger mapLevel;
}

@property (nonatomic, strong) UILabel * addressLabel;

@property (nonatomic, strong) NSMutableArray * annotationArray;

@property (nonatomic, strong) UITextField * searchTextField;

@end

@implementation MapViewController

double latitudeOfEntity;
double longitudeOfEntity;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor greenColor];
    self.title = @"ZC_Map";
    
    _annotationArray = [[NSMutableArray alloc] init];

    _mapView = [[BMKMapView alloc] initWithFrame:self.view.frame];
    _locationService = [[BMKLocationService alloc] init];
    _locationService.delegate = self;
    [_locationService startUserLocationService];
    
    _geoCodeSearch = [[BMKGeoCodeSearch alloc] init];
    _geoCodeSearch.delegate = self;
    self.view = _mapView;
    [self createView];
    

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    [self setUpNavi];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _mapView.delegate = nil;
}


- (void)setUpNavi{
    UIBarButtonItem * barButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = barButtonItem;
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationController.navigationBar.translucent = NO;
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"搜索" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 30, 44);
    [button setTitleColor:[tool getColor:appgreen] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:12];
    [button addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightbut=[[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightbut;
    
    _searchTextField = [[UITextField alloc] initWithFrame:CGRectMakeEx(0, 0, 280, 30)];
    _searchTextField.layer.cornerRadius = 3.f;
        _searchTextField.placeholder = @"输入你想要搜索的位置";
    _searchTextField.backgroundColor = [tool getColor:backGray];
    _searchTextField.font = [UIFont systemFontOfSize:12];
    _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    _searchTextField.returnKeyType=UIReturnKeySearch;
    _searchTextField.delegate = self;
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    view.backgroundColor = [tool getColor:backGray];
    UIImageView * iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 2.5, 25, 25)];
    
    iconImageView.image = [UIImage imageNamed:@"iconfont-sousuo"];
    [view addSubview:iconImageView];
    _searchTextField.leftView = view;
    
    self.navigationItem.titleView = _searchTextField;
    
    self.navigationController.navigationBar.tintColor = [tool getColor:textColorBlack];

}


-(void)back
{
    CATransition *transition = [CATransition animation];
    transition.duration = 1.0f;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = @"rippleEffect";
    transition.subtype = kCATransitionFromRight;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)search{
    NSLog(@"search");
    
    [self returnCoordWithAddress:_searchTextField.text];

    
}

- (void)createView{
    // 放大缩小地图
    UIView * btnView = [[UIView alloc] initWithFrame:CGRectMake(widthEx(11), heightEx(SCREEN_HEIGHT - 180 - 23 - 80), 43, 80)];
    [self.view addSubview:btnView];
    btnView.layer.borderWidth = 0.5f;
    btnView.backgroundColor = [UIColor whiteColor];
    btnView.layer.borderColor = [tool getColor:borderColorGray].CGColor;
    btnView.layer.cornerRadius = 2.0f;
    btnView.layer.masksToBounds = YES;
    
    for (int i = 0; i < 2; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, i * 41, 43, 40);
        button.titleLabel.font = [UIFont systemFontOfSize:23];
        [button setTitle:i == 0 ? @"+" : @"-" forState:UIControlStateNormal];
        [button setTitleColor:[tool getColor:borderColorGray] forState:UIControlStateNormal];
        [button addTarget: self action:@selector(mapLevel:) forControlEvents:UIControlEventTouchUpInside];
        [btnView addSubview:button];
    }
    
    UIView * centerLine = [[UIView alloc] initWithFrame:CGRectMake(7, 40, 29, 0.5)];
    centerLine.backgroundColor = [tool getColor:borderColorGray];
    [btnView addSubview:centerLine];
    
    
    // 定位图标
    UIImageView * locationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(widthEx(11), heightEx(SCREEN_HEIGHT - 180), 43, 41)];
    locationImageView.image = [UIImage imageNamed:@"icon"];
    locationImageView.userInteractionEnabled = YES;
    [locationImageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(locationToYourself)]];
    [self.view addSubview:locationImageView];
    
    // 顶部视图
    _topView = [[UIView alloc] initWithFrame:CGRectMakeEx(0, 0, 375, 47)];
    _topView.backgroundColor = [tool getColor:appgreen];
    _topView.alpha = 0.9f;
    [self.view addSubview:_topView];
    
    UIImage * pointImage = [UIImage imageNamed:@"iconfont-dangqiandizhizuobiao"];
    UIImageView * pointImageView = [[UIImageView alloc] initWithImage:pointImage];
    [_topView addSubview:pointImageView];
    
    pointImageView.centerY = 47 / 2;
    pointImageView.centerX = 24 + pointImage.size.width / 2;
    
    CGFloat labelX = 38 + pointImage.size.width;
    CGFloat labelY = 0;
    CGFloat labelW = 375 - labelX - 20;
    CGFloat labelH = 47;
    
    _addressLabel = [[UILabel alloc] initWithFrame:CGRectMakeEx(labelX, labelY, labelW , labelH)];
    _addressLabel.textColor = [tool getColor:textColorBlack];
    _addressLabel.text = @"上善若水";
    _addressLabel.numberOfLines = 2;
    _addressLabel.font = [UIFont systemFontOfSize:13];
    [_topView addSubview:_addressLabel];
    
    NSArray * btnArray = @[@"实时 路况",@"显示 罗盘",@"其他 功能"];
    for (int i = 0; i < btnArray.count; i++) {
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(widthEx(375 - 44), 150 - 64 + i * 39, 33, 33)];
        label.layer.cornerRadius = 2.0f;
        label.layer.borderColor = [tool getColor:borderColorGray].CGColor;
        label.layer.borderWidth = 0.5f;
        label.layer.masksToBounds = YES;
        label.backgroundColor = [tool getColor:backColor];
        label.text = btnArray[i];
        label.numberOfLines = 2;
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = LABELTAG + i;
        label.alpha = 0.5;
        label.font = [UIFont systemFontOfSize:11];
        label.textColor = [tool getColor:white];
        label.userInteractionEnabled = YES;
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapType:)]];
        [self.view addSubview:label];
    }

}

- (void)mapType:(UITapGestureRecognizer *)tap{
    
    UILabel * label = (UILabel *)tap.view;
    
    if ([label.text isEqualToString:@"实时 路况"]) {
        static int i = 0;
        i++;
        if (i % 2) {
            [_mapView setTrafficEnabled:YES];
            label.backgroundColor = [tool getColor:appgreen];
            label.textColor = [tool getColor:textColorBlack];
        }else{
            [_mapView setTrafficEnabled:NO];
            label.backgroundColor = [tool getColor:backColor];
            label.textColor = [UIColor whiteColor];
        }
    }else if ([label.text isEqualToString:@"显示 罗盘"]){
        
        label.text = @"关闭 罗盘";
        
        _mapView.showsUserLocation = NO;
        
        _mapView.userTrackingMode = BMKUserTrackingModeFollowWithHeading;
        
        _mapView.showsUserLocation = YES;
    }else if ([label.text isEqualToString:@"关闭 罗盘"]){
        label.text = @"显示 罗盘";
        
        _mapView.showsUserLocation = NO;
        
        _mapView.userTrackingMode = BMKUserTrackingModeFollow;
        
        _mapView.showsUserLocation = YES;
    }else if ([label.text isEqualToString:@"其他 功能"]){
        FucViewController * fuc = [[FucViewController alloc] init];
        [self.navigationController pushViewController:fuc animated:YES];
    }
    
}


- (void)cleanAnnotations{
    [_mapView removeAnnotations:_annotationArray];
    [_annotationArray removeAllObjects];
}



#pragma mark - 放大缩小地图
- (void)mapLevel:(UIButton *)button{
    mapLevel = _mapView.zoomLevel;
    if ([button.titleLabel.text isEqualToString:@"+"]) {
        NSLog(@"放大地图");
        mapLevel++;
        if (mapLevel >= 20) {
            mapLevel = 20;
        }
        [_mapView setZoomLevel:mapLevel];
    }else{
        NSLog(@"缩小地图");
        mapLevel--;
        if (mapLevel <= 3) {
            mapLevel = 3;
        }
        [_mapView setZoomLevel:mapLevel];
    }
}

- (void)locationToYourself{
    
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
//    _mapView.userTrackingMode = BMKUserTrackingModeFollowWithHeading;
    
    _mapView.showsUserLocation = YES;
//    if (_mapView.userLocation.location != nil) {
//        NSLog(@"定位成功");
//    }
    
    _locationService.desiredAccuracy = kCLLocationAccuracyBest;
    
    [_mapView updateLocationData:_locationService.userLocation];
    
    [_mapView setCenterCoordinate:_locationService.userLocation.location.coordinate];
    
    [_mapView setZoomLevel:15];
    
    [self returnAddressWith:_locationService.userLocation.location.coordinate];
    
    [self.view addSubview:_topView];
}
#pragma mark - 根据经纬度返回地理位置
- (void)returnAddressWith:(CLLocationCoordinate2D)pointAddress{
    BMKReverseGeoCodeOption * reverseGeoCodeOption = [[BMKReverseGeoCodeOption alloc] init];
    reverseGeoCodeOption.reverseGeoPoint = pointAddress;
    BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
    if (flag) {
        NSLog(@"反地理编码成功");
    }else{
        NSLog(@"反地理编码失败");
    }
}

#pragma mark - 根据地理位置返回经纬度
- (void)returnCoordWithAddress:(NSString *)address{
    BMKGeoCodeSearchOption * searchOption = [[BMKGeoCodeSearchOption alloc] init];
    searchOption.address = address;
    BOOL flag = [_geoCodeSearch geoCode:searchOption];
    if (flag) {
        NSLog(@"地理编码成功");
    }else{
        NSLog(@"地理编码失败");
    }
}

#pragma mark - 地理编码/反地理编码
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        NSLog(@"结果：%@；搜索：%@",result,searcher);
        _addressLabel.text = result.address;
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}

- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        NSLog(@"结果：%@；搜索：%@",result,searcher);
        
        latitudeOfEntity = result.location.latitude;
        longitudeOfEntity = result.location.longitude;
        
        [self addPointAnnotation];
        [_mapView setCenterCoordinate:result.location];
        
    }else{
        [MBProgressHUD showError:@"抱歉，未找到结果"];
    }
}

#pragma mark - 点击地图后回调
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate{
    [self returnAddressWith:coordinate];
    
    latitudeOfEntity = coordinate.latitude;
    longitudeOfEntity = coordinate.longitude;
    
    [_searchTextField resignFirstResponder];
    
    [self cleanAnnotations];
    
    [self addPointAnnotation];
}


#pragma mark - 添加当前位置的标注
-(void)addPointAnnotation {
    CLLocationCoordinate2D coord;
    coord.latitude = latitudeOfEntity;
    coord.longitude = longitudeOfEntity;
    
    _pointAnnotation = [[BMKPointAnnotation alloc] init];
    
    [_annotationArray addObject:_pointAnnotation];
    
    _pointAnnotation.coordinate = coord;
    _pointAnnotation.title = @"当前位置";
    dispatch_async(dispatch_get_main_queue(), ^{
//        [_mapView setCenterCoordinate:coord animated:YES];
        [_mapView addAnnotation:_pointAnnotation];
    });
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    NSLog(@"annotationView————————————————————————————————————————————————");

    NSString *AnnotationViewID = @"renameMark";
    BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        
        annotationView.animatesDrop = YES;
        // 设置可拖拽
        annotationView.draggable = YES;
        annotationView.image = [UIImage imageNamed:@"map_pin_stroke_20"];
    }
    return annotationView;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    [_mapView updateLocationData:userLocation];
}


@end
